package org.test.jf.web;

import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.test.jf.domain.User;
import org.test.jf.exception.AppException;
import org.test.jf.service.UserService;
import org.test.jf.util.ServiceUtil;

public class UserServlet extends HttpServlet {

	public UserService userService;
	
	@Override
	public void init() throws ServletException {
		ServiceUtil.getServiceInfo(this);
	}

	@Override
	public void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
		String method = request.getParameter("method");
		if(null == method) {
			throw new AppException("请求方法错误");
		}
		Class clazz = this.getClass();
		try {
			Method doMethod = clazz.getDeclaredMethod(method, new Class[]{HttpServletRequest.class,HttpServletResponse.class});
			String path = (String) doMethod.invoke(this, request,response);
			request.getRequestDispatcher(path).forward(request, response);
		} catch (SecurityException e) {
			e.printStackTrace();
			throw e;
		} catch (NoSuchMethodException e) {
			e.printStackTrace();
			throw new AppException("请求方法错误");
		} catch (IllegalArgumentException e) {
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		} catch (InvocationTargetException e) {
			e.printStackTrace();
		}
	}

	public String add(HttpServletRequest request, HttpServletResponse response) {
		User user = new User();
		userService.add(user);
		return "index.jsp";
	}

	public UserService getUserService() {
		return userService;
	}

	public void setUserService(UserService userService) {
		this.userService = userService;
	}
	
}
